﻿using Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;

namespace ZBZH_Manage_Order.Controllers.MerchantsSettings
{
    public class MerSetController : Controller
    {
        //
        // GET: /MerSet/
        ServiceReference1.Service1Client wsdcser = new ServiceReference1.Service1Client();
        ZHHQSERVICE.Service1Client service = new ZHHQSERVICE.Service1Client();

        public ActionResult Index()
        {
            return View();
        }
        #region 获取商户信息grid
        /// <summary>
        ///获取商户信息grid列表 
        /// </summary>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult getmer(JqGridParam jqgridparam)
        {
            try
            {
                Page<View_Order_MerSet> page = new Page<View_Order_MerSet>();
                List<Model.View_Order_MerSet> List = new List<Model.View_Order_MerSet>();
                List = GetAllMer();
                if (List.Count > 0)//返回结果正常
                {
                    jqgridparam.records = List.Count;//查询的数据总数
                    var data = new
                    {
                        total = List.Count.ToString(),
                        rows = page.FindListPage(List, ref jqgridparam)//返回当前页的数据
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = List.Count.ToString(),
                        rows = List
                    };
                    return Json(data);
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 获取商户类型
        /// <summary>
        /// 获取商户类型
        /// </summary>
        /// <returns></returns>
        public ActionResult getmertype()
        {
            List<Basic_Dict_T> ls = new List<Basic_Dict_T>();
            ls = PublicMethod.GetDict.GetList(34);

            // 添加全部选项按钮
            Basic_Dict_T add = new Basic_Dict_T();
            add.DictName = "全部";
            add.DictKey = "-8989";
            ls.Insert(0, add);
            return Json(ls, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 更新商户设置
        /// <summary>
        /// 修改商户设置
        /// </summary>
        /// <returns></returns>
        public ActionResult updatemerset(Model.View_Order_MerSet upms)
        {

            try
            {
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];
                int uid = user.OperID;

                #region 转换传入的商户信息
                Model.Order_Mer_T newmer = new Model.Order_Mer_T();
                newmer.DelFormMon = int.Parse((upms.DelFormMon * 100).ToString());
                newmer.DelMaxMon = int.Parse((upms.DelMaxMon * 100).ToString());
                newmer.DelTime = upms.DelTime;
                newmer.DelType = upms.DelType;
                newmer.EvaCount = upms.EvaCount;
                newmer.IsRet = upms.IsRet;
                newmer.LastChanMon = upms.LastChanMon;
                newmer.MerAdr = upms.MerAdr;
                newmer.MerCall = upms.MerCall;
                newmer.MerDep = upms.MerDep;
                newmer.MerID = upms.MerID;
                newmer.MerName = upms.MerName;
                newmer.MerPic = upms.MerPic;
                newmer.MerSort = upms.MerSort;
                newmer.MerState = 1;
                newmer.MerTxt = upms.MerTxt;
                newmer.OverChanMon = upms.OverChanMon;
                newmer.SalesCount = upms.SalesCount;
                newmer.StarCount = upms.StarCount;
                newmer.IsCashPay = upms.IsCashPay;
                newmer.Greater = upms.Greater;
                newmer.HowCount = upms.HowCount;
                newmer.AddMoney = upms.AddMoney;
                newmer.DelMonTxt = upms.DelMonTxt;
                #endregion

                string json = newmer.ToJson();
                string result = wsdcser.SetOrder_Mer(uid, json, 2, "", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();

                if (bs == "1")
                {
                    return Content("OK");
                }
                else
                {
                    return Content("False");
                }
            }
            catch (Exception)
            {
                //return null;
                return RedirectToAction("LoginPage", "Login"); //czx:当session失效时，自动跳转到登录页面
            }
        }
        #endregion

        #region 允许消费范围
        /// <summary>
        /// 获取允许消费范围
        /// </summary>
        /// <returns></returns>
        public ActionResult getdep()
        {
            try
            {
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login"); //czx:当session失效时，自动跳转到登录页面
                }

                List<TreeJsonEntity> TreeList = new List<TreeJsonEntity>();
                //int uid= user.OperID;
                string result = service.GetDepatMentNoValidate(GetYZM._YZM, 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                List<ZBZH_Manage_Order.Models.Basic_Department_T> ls = new List<ZBZH_Manage_Order.Models.Basic_Department_T>();
                JObject jb = JObject.Parse(result);
                if (jb["BS"].ToString() == "1")//返回结果正常
                {
                    IList<JToken> jieguo = jb["rows"].Children().ToList();
                    ls = ParseClass<ZBZH_Manage_Order.Models.Basic_Department_T>.JsonList(jieguo);//解析返回的结果
                    foreach (ZBZH_Manage_Order.Models.Basic_Department_T item in ls)
                    {
                        bool hasChildren = false;
                        IList childnode = ls.FindAll(t => t.DepParentID == item.DepID);
                        if (childnode.Count > 0)
                        {
                            hasChildren = true;
                        }
                        TreeJsonEntity tree = new TreeJsonEntity();
                        tree.id = item.DepID;
                        tree.text = item.DepName;
                        tree.value = item.DepID;
                        tree.isexpand = true;
                        tree.complete = true;
                        tree.hasChildren = hasChildren;
                        tree.parentId = item.DepParentID;
                        TreeList.Add(tree);
                    }
                    string a = TreeList.TreeToJson();
                    return Content(TreeList.TreeToJson());
                }
                else
                {
                    return Json(jb["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        #endregion

        #region 获取所有商户信息
        /// <summary>
        /// 获取所有商户
        /// </summary>
        /// <returns></returns>
        public List<View_Order_MerSet> GetAllMer()
        {
            List<View_Order_MerSet> list = new List<View_Order_MerSet>();
            //string result = wsdcser.GetOrder_Mer("", 1);        
            Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

            string result = wsdcser.GetOrder_MerByOperId(user.OperID, "", 1);
            string siteUrl = ConfigurationManager.AppSettings["Photo"];
            JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
            string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
            if (bs == "1")//返回结果正常
            {
                IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                list = ParseClass<View_Order_MerSet>.JsonList(jieguo);
                foreach (View_Order_MerSet m in list)
                {
                    m.DelFormMon = m.DelFormMon * 0.01;
                    m.DelMaxMon = m.DelMaxMon * 0.01;
                }
                //        m.DelFormMon = int.Parse(DataHelper.MoneyToYuang(item["DelFormMon"].ToString()));
                //        m.DelMaxMon = int.Parse(DataHelper.MoneyToYuang(item["DelMaxMon"].ToString()));

                //if (jieguo.Count > 0)
                //{
                //    foreach (JToken item in jieguo)
                //    {
                //        // List<Model.Sys_Component_T> list_com = new List<Model.Sys_Component_T>();
                //        List<View_Order_MerSet> newlist = new List<View_Order_MerSet>();
                //        View_Order_MerSet m = new View_Order_MerSet();
                //        m.DelFormMon = int.Parse(DataHelper.MoneyToYuang(item["DelFormMon"].ToString()));
                //        m.DelMaxMon = int.Parse(DataHelper.MoneyToYuang(item["DelMaxMon"].ToString()));
                //        m.DelTime = int.Parse(item["DelTime"].ToString());
                //        m.DelType = item["DelType"].ToString();
                //        m.DictName = item["DictName"].ToString();
                //        m.EvaCount = int.Parse(item["EvaCount"].ToString());
                //        m.IsRet = int.Parse(item["IsRet"].ToString());
                //        m.LastChanMon = item["LastChanMon"].ToString();
                //        m.MerAdr = item["MerAdr"].ToString();
                //        m.MerCall = item["MerCall"].ToString();
                //        m.MerDep = item["MerDep"].ToString();
                //        m.MerName = item["MerName"].ToString();
                //        m.MerID = item["MerID"].ToString();
                //        //m.MerPic = siteUrl + item["MerPic"].ToString();
                //        m.MerPic = item["MerPic"].ToString();
                //        m.MerSort = item["MerSort"].ToString();
                //        m.MerState = int.Parse(item["MerState"].ToString());
                //        m.MerTxt = item["MerTxt"].ToString();
                //        m.OverChanMon = item["OverChanMon"].ToString();
                //        m.SalesCount = int.Parse(item["SalesCount"].ToString());
                //        m.StarCount = int.Parse(item["StarCount"].ToString());
                //        list.Add(m);
                //    }
                //}
                Session[SessionStorage.MerList] = list;//将实体类保存至Session
                return list;
            }
            else
            {
                return null;
            }

        }
        #endregion
        /// <summary>
        /// 获取菜品照片
        /// </summary>
        /// <param name="DisheID">菜品ID</param>
        /// <returns></returns>
        public ActionResult getMerPhoto(string MerID)
        {
            try
            {
                string pic = "";
                List<View_Order_MerSet> list = (List<View_Order_MerSet>)Session[SessionStorage.MerList];
                foreach (View_Order_MerSet item in list)
                {
                    if (MerID == item.MerID)
                    {
                        pic = item.MerPic;
                    }
                }
                return Content(pic);
            }
            catch (Exception) { return null; }
        }
        #region 查询商户
        public ActionResult SearchMer(string DelType, string MerName, string MerAdr, JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.View_Order_MerSet> page = new Page<Model.View_Order_MerSet>();//
                List<View_Order_MerSet> ls = GetAllMer();
                List<Model.View_Order_MerSet> newls = new List<Model.View_Order_MerSet>();//

                if (DelType == "-8989")
                {
                    ls = ls.ToList();
                }
                if (DelType != "" && DelType != "-8989")
                {
                    ls = ls.Where(i => i.DelType == DelType).ToList();
                }
                if (MerName != "")
                {
                    ls = ls.Where(i => i.MerName.IndexOf(MerName) != -1).ToList();
                }
                if (MerAdr != "")
                { ls = ls.Where(i => i.MerAdr.IndexOf(MerAdr) != -1).ToList(); }
                jqgridparam.records = ls.Count;//查询的数据总数
                var data = new
                {
                    total = ls.Count,
                    rows = page.FindListPage(ls, ref jqgridparam)//返回当前页的数据 
                };
                return Json(data);
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion
        /// <summary>
        /// 单独上传图片
        /// </summary>
        /// <returns></returns>
        public ActionResult ToLoadPic(string MerID, string PicName)
        {
            try
            {
                string daPic = System.IO.Path.Combine(Server.MapPath("~/Mers"), System.IO.Path.GetFileName(MerID + "da.jpg"));
                //string xiaoPic = System.IO.Path.Combine(Server.MapPath("~/Mers"), System.IO.Path.GetFileName("xiao.jpg"));
                byte[] dPic = GetPictureData(daPic);
                //byte[] xPic = GetPictureData(xiaoPic);
                //string url = "/Mers/" + PicName;
                string url = "/Mers/" + MerID + "da.jpg";
                string results = wsdcser.UpdateMerPhoto(MerID, dPic, GetYZM._YZM, 1);
                //string result = wsdcser.SetMerPhoto(MerID, url, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(results);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")
                {
                    //List<View_Order_MerSet> list = (List<View_Order_MerSet>)Session[SessionStorage.MerList];
                    //foreach (View_Order_MerSet item in list)
                    //{
                    //    if (item.MerID == MerID)
                    //    {
                    //        item.MerPic = url;
                    //    }
                    //}
                    //Session[SessionStorage.DisheList] = null;
                    //Session[SessionStorage.DisheList] = list;
                    return Content(bs);
                }
                else { return Content("上传失败"); }
            }
            catch (Exception ex)
            {
                string daPic = System.IO.Path.Combine(Server.MapPath("~/Mers"), System.IO.Path.GetFileName(MerID + "da.jpg"));
                byte[] dPic = GetPictureData(daPic);
                string results = wsdcser.UpdateMerPhoto(MerID, dPic, GetYZM._YZM, 1);
                string e = ex.ToString();
                string daPiclog4 = Server.MapPath("~/异常");
                if (!Directory.Exists(daPiclog4))//判断目录是否存在
                {
                    Directory.CreateDirectory(daPiclog4);
                }

                return Content(results);
            }
        }
        #region 上传图片
        /// <summary>
        /// 上传照片
        /// </summary>
        /// <param name="fileToUpload"></param>
        /// <returns></returns>
        public ActionResult ToLead(HttpPostedFileBase[] fileToUpload, string id)
        {
            try
            {
                string FileUrl = string.Empty;
                string daPic = Server.MapPath("~/Mers");
                if (!Directory.Exists(daPic))//判断目录是否存在
                {
                    Directory.CreateDirectory(daPic);
                }
                foreach (HttpPostedFileBase file in fileToUpload)
                {
                    string path = System.IO.Path.Combine(Server.MapPath("~/Mers"), System.IO.Path.GetFileName(id + file.FileName));
                    file.SaveAs(path);
                    FileUrl = path;
                    FileStream Pic = new FileStream(path, FileMode.Open);
                    byte[] PicByte = new byte[Pic.Length];
                    Pic.Read(PicByte, 0, (int)Pic.Length);
                    Pic.Close();
                    //string result = service.UpdatUserPhoto(acc, PicByte, 1, GetYZM._YZM, 1);
                }
                return Content("上传成功");
            }
            catch
            {
                return Content("上传失败");
            }
        }
        #endregion

        #region  获取商品排序表格
        /// <summary>
        /// 获取商户的所有商品
        /// </summary>
        /// <param name="MerID"></param>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult getgrid(string MerID, JqGridParam jqgridparam)
        {
            try
            {
                Page<View_Order_Dishes> page = new Page<View_Order_Dishes>();//分页类定义
                List<View_Order_Dishes> list = new List<View_Order_Dishes>();
                list = GetAllDishes(MerID);
                if (list.Count > 0)
                {
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = list.Count.ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list
                    };
                    return Json(data);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        #endregion

        #region   根据商户ID获取对应商户的所有商品
        /// <summary>
        /// 获取对应商户的所有商品
        /// </summary>
        /// <param name="MerID"></param>
        /// <returns></returns>
        public List<View_Order_Dishes> GetAllDishes(string MerID)
        {
            List<View_Order_Dishes> list = new List<View_Order_Dishes>();
            string result = wsdcser.GetOrder_Dishes(MerID, "", 1);
            string siteUrl = ConfigurationManager.AppSettings["Photo"];
            JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
            string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
            if (bs == "1")//返回结果正常
            {
                IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                if (jieguo.Count > 0)
                {
                    foreach (JToken item in jieguo)
                    {
                        // List<Model.Sys_Component_T> list_com = new List<Model.Sys_Component_T>();
                        List<View_Order_Dishes> list_Dishes = new List<View_Order_Dishes>();
                        View_Order_Dishes m = new View_Order_Dishes();
                        m.DishesID = item["DishesID"].ToString();
                        m.DishesNmae = item["DishesNmae"].ToString();
                        m.MerID = item["MerID"].ToString();
                        m.MerName = item["MerName"].ToString();
                        m.DishesTypeID = item["DishesTypeID"].ToString();
                        m.DishesEnableInt = int.Parse(item["DishesEnableInt"].ToString());
                        m.DishesIsInt = int.Parse(item["DishesIsInt"].ToString());
                        m.DishesMon = DataHelper.MoneyToYuang(item["DishesMon"].ToString());
                        m.DelPackMon = DataHelper.MoneyToYuang(item["DelPackMon"].ToString());
                        m.DishesPay = DataHelper.MoneyToYuang(item["DishesPay"].ToString());
                        m.DishesVol = int.Parse(item["DishesVol"].ToString());
                        m.DishesTxt = item["DishesTxt"].ToString();
                        m.DishesPic = siteUrl + item["DishesPic"].ToString();
                        m.DishesEvaNun = int.Parse(item["DishesEvaNun"].ToString());
                        m.DishesEvaTxt = int.Parse(item["DishesEvaTxt"].ToString());
                        m.DishesEvaX = int.Parse(item["DishesEvaX"].ToString());
                        m.DishesGood = int.Parse(item["DishesGood"].ToString());
                        m.DishesTypeState = int.Parse(item["DishesTypeState"].ToString());
                        m.IntBZ = item["IntBZ"].ToString();
                        m.DishesTypeName = item["DishesTypeName"].ToString();
                        list.Add(m);
                    }
                }
                return list;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 用于金额转换 --定义类
        /// <summary>
        /// 商品信息定义（用于金额转换）
        /// </summary>
        public class View_Order_Dishes
        {
            public int DishesEnableInt { get; set; }
            public int DishesEvaNun { get; set; }
            public int DishesEvaTxt { get; set; }
            public int DishesEvaX { get; set; }
            public int DishesGood { get; set; }
            public string DishesID { get; set; }
            public int DishesIsInt { get; set; }
            public string DishesMon { get; set; }
            public string DishesNmae { get; set; }
            public string DishesPay { get; set; }
            public string DishesPic { get; set; }
            public string DishesTxt { get; set; }
            public string DishesTypeID { get; set; }
            public string DishesTypeName { get; set; }
            public int DishesTypeState { get; set; }
            public int DishesVol { get; set; }
            public string IntBZ { get; set; }
            public string MerID { get; set; }
            public string MerName { get; set; }
            public string DelPackMon { get; set; }
        }
        #endregion

        #region 根据id获取图片
        /// <summary>
        /// #endregion
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Image(string id)
        {
            try
            {
                //FileResult
                byte[] up = wsdcser.GetMerPhoto(id, GetYZM._YZM, 1);
                Bitmap tp = BytesToBitmap(up);
                string bd = System.IO.Path.Combine(Server.MapPath("~/Mers"), System.IO.Path.GetFileName(id + "bd.jpg"));
                tp.Save(bd);
                //byte[] image = service.GetPhoto(id, 1, GetYZM._YZM, 1);
                //return new FileContentResult(image, "image/jpeg");
                return Content(bd);
            }
            catch (Exception es)
            {
                return Content("获取图片失败");
            }
        }
        #endregion

        #region byte转Bitmap
        /// <summary>
        /// byte转Bitmap
        /// </summary>
        /// <param name="Bytes"></param>
        /// <returns></returns>
        public static Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new Bitmap((Image)new Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }
        #endregion

        #region 图片转byte
        /// <summary>
        /// 图片转byte
        /// </summary>
        /// <param name="imagepath"></param>
        /// <returns></returns>
        public byte[] GetPictureData(string imagepath)
        {
            /**/
            ////根据图片文件的路径使用文件流打开，并保存为byte[] 
            FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法 
            byte[] byData = new byte[fs.Length];
            fs.Read(byData, 0, byData.Length);
            fs.Close();
            return byData;
        }
        #endregion

        #region 裁剪图片
        /// <summary>
        /// 裁剪图片
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <param name="pw"></param>
        /// <param name="ph"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public ActionResult SaveImg(int x, int y, int w, int h, int pw, int ph, string t, string id)
        {
            try
            {
                WriteLog.WriteErrLog("进去裁剪图片", "开始位置");
                //string du= Session["startDate"].ToString();
                string path = System.IO.Path.Combine(Server.MapPath("~/Mers"), System.IO.Path.GetFileName(id + t));
                string daPic = System.IO.Path.Combine(Server.MapPath("~/Mers"), System.IO.Path.GetFileName(id + "da.jpg"));
                ///string xiaoPic = System.IO.Path.Combine(Server.MapPath("~/Mers"), System.IO.Path.GetFileName(id+"xiao.jpg"));
                //Bitmap source = new Bitmap("E:/" + t);
                Bitmap source = new Bitmap(path);
                Bitmap resizeBitmap = new Bitmap(pw, ph);
                Graphics g = Graphics.FromImage(resizeBitmap);
                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(source, new Rectangle(0, 0, pw, ph), new Rectangle(0, 0, source.Width, source.Height), GraphicsUnit.Pixel);
                g.Dispose();

                Bitmap newImg = new Bitmap(w, h, PixelFormat.Format24bppRgb);
                g = Graphics.FromImage(newImg);
                g.DrawImage(resizeBitmap, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), GraphicsUnit.Pixel);
                g.Dispose();
                Bitmap bm2 = new Bitmap(newImg, 120, 120);
                bm2.Save(daPic);
                //Bitmap bm1 = new Bitmap(newImg, 94, 94);
                //bm1.Save(xiaoPic);
                newImg.Dispose();

                return Content("1");
                WriteLog.WriteErrLog("进去裁剪图片", "异常位置");
            }
            catch (Exception ex)
            {
                WriteLog.WriteErrLog("进去裁剪图片", "异常位置");
                return Content("裁剪图片失败");
            }

        }
        #endregion
    }
}
